import { ref, reactive, computed } from "vue";
import type { FormInstance } from "element-plus";
import { checkMobile, checkAffirmPwd } from "../../config/";
import { userLogin, userRegister, editPwd as forgetPwd } from "../../service/user/";
import Cookies from "js-cookie";
import { useUserStore } from "../../store/user";
import { closeDialog } from "../../utils/zlDialog";
import { openBindAreaDialog } from "../../utils/bindAreaDialog"
import { getPhoneCode } from "../../service/user"
import { useSearchStore } from "../../store/search";


export const useLoginCard = () => {
  const userStore: any = useUserStore();
  const searchStore: any = useSearchStore();
  const address = computed(() => userStore.userInfo?.areaName)

  // 控制组件的显示与隐藏
  const closeLoginDialog = () => {
  };

  /**
   * 登录注册逻辑
   */
  const currModel = ref({ type: "login", msg: "没有账号？立即注册", target: "register" });
  const isRememberPwd = ref(true);
  const form = reactive({
    account: Cookies.get("username"),
    password: Cookies.get("password"),
    code: "",
    mobile: "",
    registerUn: "",
    registerPwd: "",
    affirmPwd: "",
    imgVerify: "",
    forgetPwd: "",
    forgetAffirmPwd: "",
  });


  // 登录
  const loginRules = reactive({
    password: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur"
      },
      { min: 6, max: 20, message: "密码长度应在6~20之间", trigger: "blur" }
    ],
    account: [
      {
        required: true,
        message: "账号不能为空",
        trigger: "blur"
      },
      { min: 5, max: 20, message: "账号长度应在5~20之间", trigger: "blur" }
    ],
    imgVerify: [
      {
        required: true,
        message: "请进行验证",
        trigger: "change"
      }
    ]
  });
  const imgVerifySuccess = () => {
    form.imgVerify = "1";
  };
  const loginLoading = ref(false)
  const login = async (loginForm: FormInstance, captchaRef: any) => {
    try {
      const passValid = await loginForm.validate((valid) => valid);

      if (!passValid) return;

      loginLoading.value = true

      // 发送网络请求
      const { password, account } = form;
      const res = await userLogin({ username: account, password })

      if (res.code != 200) {
        form.imgVerify = "";
        loginLoading.value = false
        return captchaRef.reset(false);
      }

      // 将token储存在cookie中
      Cookies.set("token", res.token, { expires: 7 });

      // 获取到用户数据后进行储存到pinia中
      await userStore.getUserInfo();

      // 勾选了记住账号密码则将用户的账号密码储存在cookie中
      if (isRememberPwd.value) {
        Cookies.set("username", form.account || "");
        Cookies.set("password", form.password || "");
      } else {
        Cookies.remove("username")
        Cookies.remove("password")
      }

      searchStore.getDictDatas()
      // 关闭弹窗
      loginLoading.value = false
      closeDialog()
      userStore.updateUserAuth()
      // alert("选择地区")
      if (!address.value) return openBindAreaDialog()
      // 调用权限
      // userStore.updateUserAuth()
      // 刷新页面
      location.reload()
    } catch (error) {
      // 发生错误后进行验证码刷新
      captchaRef.reset(false);
      form.imgVerify = "";
    }
  };

  // 注册
  const registerRules = reactive({
    registerUn: [
      {
        required: true,
        message: "账号不能为空",
        trigger: "blur"
      },
      { min: 5, max: 20, message: "账号长度应在5~20之间", trigger: "blur" }
    ],
    mobile: [
      {
        required: true,
        validator: checkMobile,
        trigger: "blur"
      }
    ],
    code: [
      {
        required: true,
        message: "验证码不能为空",
        trigger: "blur"
      }
    ],
    registerPwd: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur"
      },
      { min: 6, max: 20, message: "密码长度应在6~20之间", trigger: "blur" }
    ],
    affirmPwd: [
      {
        required: true,
        validator: (rule: any, value: any, callback: any) => {
          checkAffirmPwd(rule, value, callback, form.registerPwd);
        },
        trigger: "blur"
      }
    ]
  });
  const register = async (registerForm: FormInstance) => {
    // 验证注册表单
    const passValid = await registerForm.validate((valid) => valid);

    if (!passValid) return;

    const params = { username: form.registerUn, password: form.registerPwd, phone: form.mobile, code: form.code };

    // 发送网络请求
    userRegister(params).then((res) => {
      if (res.code == 200) {
        // 如果为200说明注册成功,给予用户提示并跳转到登录界面
        ElMessage({
          message: "注册成功~",
          type: "success",
          grouping: true
        });
        currModel.value = { type: "login", msg: "已有账号，立即登录", target: "register" };
        form.affirmPwd = "";
        form.registerPwd = "";
        form.registerUn = "";
      }
    });
  };

  // 忘记密码
  const forgetRules = reactive({
    mobile: [
      {
        required: true,
        validator: checkMobile,
        trigger: "blur"
      }
    ],
    code: [
      {
        required: true,
        message: "验证码不能为空",
        trigger: "blur"
      }
    ],
    forgetPwd: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur"
      },
      { min: 6, max: 20, message: "密码长度应在6~20之间", trigger: "blur" }
    ],
    forgetAffirmPwd: [
      {
        required: true,
        validator: (rule: any, value: any, callback: any) => {
          checkAffirmPwd(rule, value, callback, form.forgetPwd);
        },
        trigger: "blur"
      }
    ]
  });

  const editPwd = async (forgetPwdForm: FormInstance) => {
    // 验证注册表单
    const passValid = await forgetPwdForm.validate((valid) => valid);

    if (!passValid) return;

    const params = { phone: form.mobile, password: form.forgetPwd, code: form.code };

    // 发送网络请求
    forgetPwd(params).then((res) => {
      if (res.code == 200) {
        // 如果为200说明注册成功,给予用户提示并跳转到登录界面
        ElMessage({
          message: "密码修改成功~",
          type: "success",
          grouping: true
        });
        currModel.value = { type: "login", msg: "没有账号？立即注册", target: "register" };
        form.affirmPwd = "";
        form.registerPwd = "";
        form.registerUn = "";
      }
    });
  }

  // 更换面板模式
  const changeModel = (type: any) => {
    switch (type) {
      case "login":
        currModel.value = { type: "login", msg: "没有账号？立即注册", target: "register" }
        break;
      case "register":
        currModel.value = { type: "register", msg: "已有账号，立即登录", target: "login" };
        break;
      case "forgetPwd":
        currModel.value = { type: "forgetPwd", msg: "立即登录", target: "login", }
        break;
    }
  };

  // 手机验证码
  const btnText = ref<string | number>("获取验证码");
  const getVerifyCode = async (formEl: FormInstance, type: "1" | "2") => {
    let passValid = true;
    // 判断手机号格式是否正确(单独验证)
    await formEl.validateField(["mobile"], async (valid) => {
      if (!valid) passValid = false;
    });
    // 验证不通过直接返回
    if (!passValid) return;
    // 发送网络请求
    getPhoneCode({ phone: form.mobile, templateCode: type })
    btnText.value = "60s后重试";
    let time = 60;
    const timer = setInterval(() => {
      time--;
      if (time >= 0) {
        btnText.value = time + "s后重试";
      } else if (time < 0) {
        btnText.value = "获取验证码";
        clearInterval(timer);
        time = 60;
      }
    }, 1000);
  };

  return {
    isRememberPwd,
    form,
    login,
    loginLoading,
    register,
    currModel,
    changeModel,
    getVerifyCode,
    btnText,
    registerRules,
    loginRules,
    imgVerifySuccess,
    editPwd,
    forgetRules
  };
};
